/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.google.api.search;

import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;

import main.Main;

import org.jibble.pircbot.Colors;
import org.json.JSONArray;
import org.json.JSONObject;

import tools.StringTools;

import com.google.api.GoogleAPI;

public final class Search extends GoogleAPI {

   /**
    * Constants.
    */
   private static final String URL = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&",
		 PARAMETERS = "key=#KEY#&rsz=small&q=";

   public static List<String> execute(final String text) throws Exception {
	  validateReferrer();
	  if (StringTools.isNullOrEmpty(Main.getBotSettings().getGoogleAPIKey()))
		 throw new Exception("Google API key is missing");

	  String parameters = PARAMETERS;
	  parameters = parameters.replaceAll("#KEY#", Main.getBotSettings().getGoogleAPIKey()) + URLEncoder.encode(text, ENCODING);
	  final URL url = new URL(URL + parameters);

	  final JSONObject json = retrieveJSON(url);
	  if (json == null)
		 throw new NullPointerException();
	  return getJSONResponse(json);
   }

   private static List<String> getJSONResponse(final JSONObject json) throws Exception {
	  List<String> out = new LinkedList<String>();
	  JSONArray list = json.getJSONObject("responseData").getJSONArray("results");
	  for (int i = 0; i < list.length() && i < 3; ++i) {
		 JSONObject obj = list.getJSONObject(i);
		 if (obj != null) {
			out.add(obj.getString("titleNoFormatting") + " - "
				  + obj.getString("content").replaceAll("\\<.*?\\>", "").replaceAll("&#39;", "'").replaceAll("&quot;", "\""));
			out.add(Colors.BLUE + obj.getString("url"));
		 }
	  }
	  return out;
   }
}